package cz.proks.easyhelpdesk.gae.api.impl.db;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import cz.proks.easyhelpdesk.api.TicketApi;
import cz.proks.easyhelpdesk.api.config.Configuration;
import cz.proks.easyhelpdesk.api.exception.ApiException;
import cz.proks.easyhelpdesk.api.model.Ticket;

@Repository(Configuration.DB.TICKET_API)
@Scope("prototype")
public class TicketApiImpl extends BaseApiImpl<Ticket> implements TicketApi {
	private final Logger log = LoggerFactory.getLogger(getClass());
		
	@Override
	protected Class<Ticket> getDomainClass() {
		return Ticket.class;
	}

    @Override
    protected Ticket getDboObject(Ticket entity) {
        cz.proks.easyhelpdesk.gae.api.impl.dbo.Ticket dbo = instantiateDbo(entity);

        if (dbo != null)
            dbo.toDbo(entity);

        return dbo;
    }
    
    @Override
    @Transactional(readOnly = false)
    public Long create(Ticket entity) throws ApiException {
        log.debug("create():: Start with entity '{}'", entity);

        cz.proks.easyhelpdesk.gae.api.impl.dbo.Ticket dbo = (cz.proks.easyhelpdesk.gae.api.impl.dbo.Ticket) getDboObject(entity);        
        
        try { getEntityManager().persist(dbo); }
        catch(Exception e) {
            throw new ApiException(e);
        }
        
        Long id = dbo != null ? dbo.getId() : null;
        
        BeanUtils.copyProperties(dbo, entity);
        
        log.debug("create():: End with id '{}'", id);
        return id;
    }       
}
